package com.ccp.learning.udp.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ShutdownManager {
    private static final Logger logger =
            LoggerFactory.getLogger(ShutdownManager.class);
    private static final List<DataProcessor> processors = new ArrayList<>();
    private static final ScheduledExecutorService monitorExecutor =
            Executors.newSingleThreadScheduledExecutor();

    public static synchronized void registerProcessor(DataProcessor processor) {
        processors.add(processor);
    }

    public static void registerShutdownHook() {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            logger.info("启动优雅停机流程");

            // 阶段1：停止接收新数据
            logger.info("关闭UDP接收端口");
            UDPServer.closeSocket();

            // 阶段2：停止所有处理线程
            logger.info("停止数据处理线程");
            processors.forEach(DataProcessor::stop);

            // 阶段3：监控剩余任务
            monitorExecutor.scheduleAtFixedRate(() -> {
                int remaining = UDPServer.get();
                logger.info("剩余待处理数据: {}", remaining);
                if (remaining == 0) {
                    System.exit(0);
                }
            }, 1, 1, TimeUnit.SECONDS);

            // 阶段4：强制终止保护
            monitorExecutor.schedule(() -> {
                logger.error("强制终止等待超时的任务");
                System.exit(1);
            }, 300, TimeUnit.SECONDS);
        }));
    }
}